package model

import (
	"context"
	"database/sql"
	"time"
)

type RobotCode struct {
	ID         int       `json:"id"`
	UserID     int       `json:"user_id"`
	RobotID    string    `json:"robot_id"`
	Status     int       `json:"status"`
	ExpireTime time.Time `json:"expire_time"`
	CreateTime time.Time `json:"create_time"`
}

type RobotCodeModel struct {
	db *sql.DB
}

func NewRobotCodeModel(db *sql.DB) *RobotCodeModel {
	return &RobotCodeModel{db: db}
}

// CreateRobotCode 创建机器码
func (m *RobotCodeModel) CreateRobotCode(ctx context.Context, code *RobotCode) error {
	result, err := m.db.ExecContext(ctx, `
		INSERT INTO wqyf_robot_codes (user_id, robot_id, status, expire_time)
		VALUES (?, ?, ?, ?)
	`, code.UserID, code.RobotID, code.Status, code.ExpireTime)
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	code.ID = int(id)

	return nil
}

// GetRobotCodes 获取用户的机器码列表
func (m *RobotCodeModel) GetRobotCodes(ctx context.Context, userID int) ([]*RobotCode, error) {
	rows, err := m.db.QueryContext(ctx, `
		SELECT id, user_id, robot_id, status, expire_time, create_time
		FROM wqyf_robot_codes
		WHERE user_id = ?
		ORDER BY create_time DESC
	`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var codes []*RobotCode
	for rows.Next() {
		code := &RobotCode{}
		err := rows.Scan(
			&code.ID,
			&code.UserID,
			&code.RobotID,
			&code.Status,
			&code.ExpireTime,
			&code.CreateTime,
		)
		if err != nil {
			continue
		}
		codes = append(codes, code)
	}

	return codes, nil
}

// GetRobotCode 获取单个机器码信息
func (m *RobotCodeModel) GetRobotCode(ctx context.Context, robotID string) (*RobotCode, error) {
	code := &RobotCode{}
	err := m.db.QueryRowContext(ctx, `
		SELECT id, user_id, robot_id, status, expire_time, create_time
		FROM wqyf_robot_codes
		WHERE robot_id = ?
	`, robotID).Scan(
		&code.ID,
		&code.UserID,
		&code.RobotID,
		&code.Status,
		&code.ExpireTime,
		&code.CreateTime,
	)

	if err != nil {
		return nil, err
	}

	return code, nil
}

// UpdateRobotCode 更新机器码状态
func (m *RobotCodeModel) UpdateRobotCode(ctx context.Context, code *RobotCode) error {
	_, err := m.db.ExecContext(ctx, `
		UPDATE wqyf_robot_codes 
		SET status = ?, expire_time = ?
		WHERE id = ?
	`, code.Status, code.ExpireTime, code.ID)
	return err
}

// DeleteRobotCode 删除机器码
func (m *RobotCodeModel) DeleteRobotCode(ctx context.Context, id int) error {
	_, err := m.db.ExecContext(ctx, `
		DELETE FROM wqyf_robot_codes
		WHERE id = ?
	`, id)
	return err
}

// GenerateRobotID 生成机器码
func (m *RobotCodeModel) GenerateRobotID() string {
	// 生成32位随机字符串
	const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
	result := make([]byte, 32)
	for i := range result {
		result[i] = charset[time.Now().UnixNano()%int64(len(charset))]
	}
	return string(result)
} 